import React from 'react'
import {  Toast } from 'antd-mobile'
import { connect } from 'react-redux';
import moment from 'moment';

import { getStepData, postEquipment, getLogin, getDingData, getRoleParam } from './common/service';
import { saveData, saveEquipment, saveFlowId, saveRoles } from './action/UserAction';
import { AGENT_ID } from './common/systemParam'

//步骤条
import Step from './container/Step';

//标识摆放确认页面
import Tip from './container/Tip';

//安检确认页面
import SecurityCheck from './container/SecurityCheck';

//施工计划录入页面
import ConstructionInput from './container/ConstructionInput';

//填写进场时间进场路线
import InitConstruction from './container/InitConstruction';

//确认施工页面
import CheckConstruction from './container/CheckConstruction';

//确认通知
import CheckNotify from './container/CheckNotify';

//安检集结确认人员设备
// import ComfirePeopleEquire from './container/ComfirePeopleEquire';

//完成施工页面
import CompeleteConstruction from './container/CompeleteConstruction';

//复查阶段监理确认
import SupervisionCheck from './container/SupervisionCheck';

//流程结束
import StepEnd from './container/StepEnd';

//安检集结安检确认
import SetSecurityCheck from './container/SetSecurityCheck';

//等待审批
import WaitCheck from './container/WaitCheck';

//手动结束
import ManualEnd from './container/ManualEnd';

import Document from './container/Document.js';


class App extends React.Component{
	constructor(props) {
		super(props);
		this.state = {
			page: 0,
			isCurrentRole: false,
			data: {
				flowBaseInfo: {
					flowProcesses: []
				}
			},
			currentObj: 0
		}
		this.modalOperation = {
			showLoadModal: ()=>this.showLoadModal(),
			hideLoadModal: ()=>this.hideLoadModal(),
			currentPage: (arr)=>this.currentPage(arr),
			changePage: (page)=>this.changePage(page),
			isTodayStep: () => this.isTodayStep()
		}
	}

	componentDidMount() { 
		// this.login(1);
		// this.getEquipment()
		// this.login(2);
		
		// this.getUserId({
		// 	corpId: 'ding4894b28ffd258be935c2f4657eb6378f',
		// 	timeStamp: '1521026355352',
		// 	nonceStr: 'ytkj',
		// 	signature: 'f7316b2abad122245fbc0d94a607df51b4974ede'
		// });
		
		// this.showLoadModal();
		// console.log(window.location.href)
		// getDingData(encodeURIComponent(window.location.href))
		// 	.then((obj) => {
		// 		const isOK = obj.data;
		// 		console.log(isOK);
		// 		if (isOK.success) {
		// 			this.getUserId(isOK.obj);
		// 		} else {
		// 			this.hideLoadModal();
		// 			Toast.info(isOK.msg);
		// 		}
		// 	})
		// 	.catch((err) => {
		// 		console.log(err);
		// 		this.hideLoadModal();
		// 		Toast.info('服务器异常');
		// 	})
	}

	// 通过钉钉数据接口获取用户id
	getUserId(obj) {
	  window.dd.config({
	    agentId: AGENT_ID, // 必填，微应用ID
	    corpId: obj.corpId,//必填，企业ID
	    timeStamp: obj.timeStamp, // 必填，生成签名的时间戳
	    nonceStr: obj.nonceStr, // 必填，生成签名的随机串
	    signature: obj.signature, // 必填，签名 
	    jsApiList : [  'biz.user.get', 'biz.navigation.close' ] 
	  });
		console.log(AGENT_ID);
    window.dd.ready(()=> {
     	window.dd.biz.user.get({
        corpId: obj.corpId, // 可选参数，如果不传则使用用户当前企业的corpId。
        onSuccess: (info) => {
        	console.log(info.emplId)
          this.login(info.emplId);
        },
        onFail: (err) => {
        	this.hideLoadModal();
          console.log('userGet fail: ' + JSON.stringify(err));
          Toast.info('用户权限校验失败');
        }
    	});
    });
    window.dd.error((err) => {
    	this.hideLoadModal();
    	Toast.info('用户权限校验失败');
     	console.log('dd.error' + JSON.stringify(err));	
    })
    // this.getRole();
	}
	//登录接口
	login(userId) {
		getLogin(userId)
		.then((obj) => {
			const isOK = obj.data;
			console.log(isOK)
			if (isOK.success) {
				global.token = isOK.obj;
				// let reqConfig = {
    //         headers: {
    //             'x-access-token': global.token
    //         }
    //     }
    //     axios.request(reqConfig);
				//记得修改回来
				this.getRole();
				// this.getStep();
				// this.getEquipment();
			} else {
				this.hideLoadModal()
				Toast.info('登录异常请刷新网页重试');
			}
		})
		.catch((err) => {
			console.log(err);
			this.hideLoadModal();
			Toast.info('服务器异常');
		})
	}
	//获取权限
	getRole(userId) {
		getRoleParam()
		.then((obj) => {
			const isOK = obj.data;
			console.log(isOK)
			if (isOK.success) {
				this.props.dispatch(saveRoles(isOK.obj));
				// this.props.dispatch(saveRoles([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,  53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75]))
				this.getStep();
				this.getEquipment();
			} else {
				this.hideLoadModal();
				Toast.info(isOK.msg);
			}
		})
		.catch((err) => {
			console.log(err);
			this.hideLoadModal();
			Toast.info('服务器异常');
		})
	}
	//获取流程
	getStep() {
		const flowId = this.getParam('flowid') * 1;
		const pageId = this.getParam('page') * 1;
		if (flowId === 0 || pageId === 0) {
			this.hideLoadModal();
			Toast.info('初始化参数失败，请正常进入网页');
			return;
		}
		this.props.dispatch(saveFlowId(flowId));
		getStepData(flowId)
			.then((data)=>{
				this.hideLoadModal();
				const isOk = data.data;
				console.log(isOk)
				if (isOk.success) {
					this.props.dispatch(saveData(isOk.obj));
					document.title = isOk.obj.flowBaseInfo.projectName;
					this.currentPage(isOk.obj.flowBaseInfo.flowProcesses);
					
					this.setState({page: this.getParam('page') * 1});
					if (isOk.obj.flowBaseInfo && isOk.obj.flowBaseInfo.status === 3 && isOk.obj.planInfoRes && isOk.obj.planInfoRes.status === 1) {
						this.setState({ page: 20 });
						return;
					}
					if (isOk.obj.review && isOk.obj.review.status === 1) {
						this.setState({
							page: 20
						});
					}
				} else {
					Toast.info(isOk.msg);
				}
			})
			.catch((e) => {
				console.log(e);
				this.hideLoadModal();
				Toast.info('服务器异常');
			})
	}
	//获取url参数
	getParam(name) {
    var search = document.location.search;
    var pattern = new RegExp("[?&]" + name + "\=([^&]+)", "g");
    var matcher = pattern.exec(search);
    var items = null;
    if (null != matcher) {
        try {
            items = decodeURIComponent(decodeURIComponent(matcher[1]));
        } catch (e) {
            try {
                items = decodeURIComponent(matcher[1]);
            } catch (e) {
                items = matcher[1];
            }
        }
    }
    return items;
  }
	//获取设备列表 
	getEquipment() {
		postEquipment()
		.then((data)=>{
			const isOK = data.data;
			console.log(isOK);
			if (isOK.success) {
				this.props.dispatch(saveEquipment(this.sortEquipmentArr(isOK.obj)));
			} else {
				Toast.info(isOK.msg);
			}
		})
	}
	//判断是否是当日流程
	isTodayStep() {
		if (moment().format('YYYY-MM-DD') ===
		 moment(this.props.userReducer.step.flowBaseInfo ? this.props.userReducer.step.flowBaseInfo.createDate : null).format('YYYY-MM-DD')) {
			return true;
		}
		return false
	}
	//整理设备列表数据格式 {value:{id:1,name:'锤子'},label:'锤子'}
	sortEquipmentArr(arrs) {
		const equipmentArr = [];
		for (const obj of arrs) {
			const equipment = {
				value: {id: obj.deviceId, name: obj.deviceName},
				label: obj.deviceName
			};
			equipmentArr.push(equipment);
		}
		return equipmentArr;
	}
	//判断当前页面
	currentPage(arr) {
		for (let i = 0, len = arr.length - 1; i< len; i++) {
			if (arr[len].state === 1) {
				this.setState({
					currentObj: arr[len]
				});
				return;
			}
			if (arr[i].state === 1 && arr[i+1].state === 0) {
				this.setState({
					currentObj: arr[i]
				})
			}
		}
	}
	//切换页面
	changePage(page) {
		this.setState({
			page: page
		})
	}
	showLoadModal() {
		Toast.loading('请稍候...', 0, ()=>{}, true);
	}

	hideLoadModal() {
		Toast.hide();
	}

	render() {
		return (
			<div className='content'>
				<div style={{display: 'flex',width: '100vw',position: 'fixed', alignItems: 'center',height: '0.8rem',paddingLeft: '0.2rem',marginBottom:'0.02rem',backgroundColor:'#323843',zIndex:'10'}}>
					<p style={{fontSize: '0.32rem',color: '#fff',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>流程名称: {this.props.userReducer.step.flowBaseInfo ? this.props.userReducer.step.flowBaseInfo.flowName : ''}</p>
				</div>
				<div style={{display: 'flex'}}> 
					<div className='left-part' style={{height: 'calc(100vh-0.8rem)', marginTop: '0.82rem',width: '2.1rem'}}>
						<Step data={this.state.data.flowBaseInfo.flowProcesses}></Step>
						
					</div>
					<div className='right-part'>
						{/*进场时间进场路线*/}
					{this.state.page === 2 ? 
						<InitConstruction {...this.modalOperation} currentObj={this.state.currentObj}></InitConstruction> : null}

						{/*施工计划录入界面*/}
					{this.state.page === 3 ? 
						<ConstructionInput {...this.modalOperation} currentObj={this.state.currentObj}></ConstructionInput> : null}

						{/*监理确认施工计划*/}
					{this.state.page === 14 ?
						<CheckConstruction {...this.modalOperation} currentObj={this.state.currentObj}></CheckConstruction> : null}

						{/*确认通知界面*/}
					{this.state.page === 5 ?
						<CheckNotify {...this.modalOperation} currentObj={this.state.currentObj}></CheckNotify> : null}

						{/*确认摆放标识界面*/}
					{this.state.page === 6 ?
						<Tip {...this.modalOperation} currentObj={this.state.currentObj}></Tip> : null}

						{/*安检集结的安检确认*/}
					{this.state.page === 7 ?
						<SetSecurityCheck {...this.modalOperation} currentObj={this.state.currentObj}></SetSecurityCheck> : null}

						{/*安检结束等待指挥部审批*/}
					{this.state.page === 8 ?
						<WaitCheck {...this.modalOperation} currentObj={this.state.currentObj}></WaitCheck> : null}

						{/*结束施工页面*/}
					{this.state.page === 15 ?
						<CompeleteConstruction {...this.modalOperation} currentObj={this.state.currentObj}></CompeleteConstruction> : null}

						{/*复查监理确认*/}
					{this.state.page === 11 ?
						<SupervisionCheck {...this.modalOperation} currentObj={this.state.currentObj}></SupervisionCheck> : null}

						{/*复查安检确认*/}
					{this.state.page === 12 ?
						<SecurityCheck {...this.modalOperation} currentObj={this.state.currentObj}></SecurityCheck> : null}

						{/*流程结束*/}
					{this.state.page === 20 ?
						<StepEnd {...this.modalOperation} currentObj={this.state.currentObj}></StepEnd> : null}

						{/*手动结束*/}
					{this.state.page === 21 ?
						<ManualEnd {...this.modalOperation} currentObj={this.state.currentObj}></ManualEnd> : null}

						{/*风险教育文档*/}
					{this.state.page === 22? 
						<Document {...this.modalOperation} currentObj={this.state.currentObj}></Document>: null
					}
					</div>
				</div>
			</div>
		);
	}
}

function mapStateToProps(state) {
  const { userReducer } = state;
  return {
    userReducer
  };
}

export default connect(mapStateToProps)(App);
